package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.wlyuan.open.scanner.assembler.ScannerRelationAssembler;
import com.wlyuan.open.scanner.config.GroupProperties;
import com.wlyuan.open.scanner.dao.mapper.SupplierMapper;
import com.wlyuan.open.scanner.domain.carrier.Relation;
import com.wlyuan.open.scanner.domain.carrier.RelationConvert;
import com.wlyuan.open.scanner.repository.RelationRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RelationRepositoryImpl implements RelationRepository {
    private final SupplierMapper supplierMapper;
    private final BaseOrderRepository baseOrderRepository;
    private final GroupProperties groupProperties;

    @Override
    public List<Relation> getRelationList() {
        var list = supplierMapper.getRelationList();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        logger.info("老数据数据量，size：{}", list.size());
        return RelationConvert.convert(list);
    }

    @Override
    public Relation getRelationByCustomerId(Long customerId) {
        var relation = supplierMapper.getRelationByCustomerId(customerId);
        return RelationConvert.convert(relation);
    }

    @Override
    public void getRelationByTenantId(Long tenantId) {
        Optional.ofNullable(tenantId).ifPresent(tenant -> {
            var list = supplierMapper.getRelationByTenantId(tenant);
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            list.forEach(data -> {
                var relation = RelationConvert.convert(data);
                baseOrderRepository.sync(ScannerRelationAssembler.assemble(relation));
                if (groupProperties.groupTenantList().contains(tenantId)) {
                    data.setCreateBy(0L);
                }
            });
        });


    }
}
